﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Shapes;

namespace CustomBehaviorLibaray
{
    public class DragInCanvasBehavior : Behavior<UIElement> {
        private Canvas canvas;

        protected override void OnAttached() {
            base.OnAttached();

            //Hook Up event handlers.
            this.AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove += AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp += AssociatedObject_MouseLeftButtonUp;
        }

        protected override void OnDetaching() {
            base.OnDetaching();

            //Hook Up event handlers.
            this.AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown;
            this.AssociatedObject.MouseMove -= AssociatedObject_MouseMove;
            this.AssociatedObject.MouseLeftButtonUp -= AssociatedObject_MouseLeftButtonUp;

        }

        //判断元素是不是在拖动
        private bool isDragging = false;

        //当鼠标点击，获取鼠标位置
        private Point mouseOffset;

        private void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { 
            //获取canvas对象
            if(this.canvas == null) {
                canvas = VisualTreeHelper.GetParent(this.AssociatedObject) as Canvas;
            }
            //开始拖动
            isDragging= true;
            //获取鼠标相对位置(元素左上角为(0,0))
            mouseOffset = e.GetPosition(AssociatedObject);
            //捕获鼠标，这个捕获动作会一直延续整个鼠标拖动的生命周期
            AssociatedObject.CaptureMouse();
        }

        private void AssociatedObject_MouseMove(object sender, MouseEventArgs e) {
            if(this.isDragging) {
                //获取相对于canvas元素的坐标(元素左上角为(0,0))
                Point point = e.GetPosition(canvas);
                //移动元素
                AssociatedObject.SetValue(Canvas.TopProperty, point.Y - mouseOffset.Y);
                AssociatedObject.SetValue(Canvas.LeftProperty, point.X - mouseOffset.X);
            }
        }

        private void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) {
            if(this.isDragging) {
                //释放鼠标
                AssociatedObject.ReleaseMouseCapture();
                //拖动结束
                isDragging= false;
            }
        }
    }
}
